import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Navigation from './components/Navigation';
import AuthPage from './components/AuthPage';
import Dashboard from './components/Dashboard';
import AlgorithmsPage from './components/AlgorithmsPage';
import './App.css';

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [token, setToken] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const storedToken = localStorage.getItem('token');
    if (storedToken) {
      setToken(storedToken);
      setIsAuthenticated(true);
    }
    setLoading(false);
  }, []);

  const handleLogin = (newToken) => {
    setToken(newToken);
    setIsAuthenticated(true);
    localStorage.setItem('token', newToken);
  };

  const handleLogout = () => {
    setToken('');
    setIsAuthenticated(false);
    localStorage.removeItem('token');
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <Router>
      <div className="app">
        <Navigation isAuthenticated={isAuthenticated} onLogout={handleLogout} />
        <Routes>
          <Route path="/" element={<Navigate to="/algorithms" />} />
          <Route path="/algorithms" element={<AlgorithmsPage />} />
          <Route 
            path="/signin" 
            element={
              isAuthenticated ? 
                <Navigate to="/dashboard" /> : 
                <AuthPage onLogin={handleLogin} />
            } 
          />
          <Route 
            path="/dashboard" 
            element={
              isAuthenticated ? (
                <Dashboard 
                  token={token} 
                  onUnauthorized={handleLogout}
                />
              ) : (
                <Navigate to="/signin" />
              )
            } 
          />
        </Routes>
      </div>
    </Router>
  );
}

export default App;